<?php

namespace app\components\lib;

use app\components\CHttp;
use app\components\CTools;

class Message {


    public $wechat;
    public function __construct(CWechat $wechat)
    {
        $this->wechat =$wechat;
    }

    public function handleMsg($r)
    {
        //心跳检测
        if(intval(date("i",time()))%5 == 0){
            $rangeTime = CTools::getTimetoDate(time() - $this->wechat->startTime);
            $scanTime = CTools::getTimetoDate(time() - $this->wechat->scanTime);
            $content = "已启动:".$rangeTime.PHP_EOL;
            $content .= "已扫码:".$scanTime;
            $this->sendTextMsg($content,'filehelper');
        }

        foreach ($r['AddMsgList'] as $msg) {

            CTools::_echo("新消息 类型:".$msg['MsgType'].PHP_EOL." 内容:".$msg['Content']);

            $msgType = $msg['MsgType'];
            $content = $msg['Content'] = CTools::br2nl(html_entity_decode($msg['Content']));
            if (substr($msg['FromUserName'], 0, 2) == '@@' && stripos($content, ':'.PHP_EOL) !== false) list($group_user_name, $content) = explode(':'.PHP_EOL, $content);

            #自己发的消息不自动回复
            if ($msg['FromUserName'] == $this->wechat->myself['UserName']) continue;
            #文本消息
            if ($msgType == 1) {
                #缓存消息
                $this->cacheMsg($msg['MsgId'],$content);
                #功能
                #****运行时间
                if($content == "运行时间" || $content =="time"){
                    $rangeTime = CTools::getTimetoDate(time() - $this->wechat->startTime);
                    $this->sendTextMsg("已运行:".$rangeTime, $msg['FromUserName']);
                    continue;
                }
                #****功能菜单**start****************
                if($content == "功能"){

                    $word = '╒═════娱乐════╕'.PHP_EOL;
                    $word .= '├╳╳╳╳╳╳╳╳╳╳╳┤'.PHP_EOL;
                    $word .= '├╳点歌╳搜图╳机器人╳┤'.PHP_EOL;
                    $word .= '├╳╳╳╳打赏夏天╳╳╳┤'.PHP_EOL;
                    $word .= '├╳╳╳╳╳╳╳╳╳╳╳┤'.PHP_EOL;
                    $word .= '╞════群═聊════╡'.PHP_EOL;
                    $word .= '├╳╳╳╳╳╳╳╳╳╳╳┤'.PHP_EOL;
                    $word .= '├╳群规╳新人入群欢迎╳┤'.PHP_EOL;
                    $word .= '├╳╳好友申请通过╳╳╳┤'.PHP_EOL;
                    $word .= '├╳╳╳撤回消息显示╳╳┤'.PHP_EOL;
                    $word .= '├╳╳╳╳╳╳╳╳╳╳╳┤'.PHP_EOL;
                    $word .= '╞════其══它═══╡'.PHP_EOL;
                    $word .= '├╳╳购买微信号请加╳╳┤'.PHP_EOL;
                    $word .= '├╳╳╳date7788╳╳╳╳┤'.PHP_EOL;
                    $word .= '├╳╳╳╳╳╳╳╳╳╳╳┤'.PHP_EOL;
                    $word .= '╘═════结束════╛'.PHP_EOL;

//                    $word .= "【点歌】【搜图】【机器人】【打赏夏天】".PHP_EOL;
//                    $word .= '=========\ue231 生活=========='.PHP_EOL;
//                    $word .= "输入'生活'更多精彩".PHP_EOL;
//                    $word .= '=========\ue231 群功能========'.PHP_EOL;
//                    $word .= "【群规】【新人入群欢迎语】".PHP_EOL;
//                    $word .= "【撤回消息显示】【好友申请自动通过】".PHP_EOL;
//                    $word .= '=========\ue231 其他========='.PHP_EOL;
//                    $word .= "购买微信号请加'date7788'为好友".PHP_EOL;


                    $this->sendTextMsg($word, $msg['FromUserName']);
                    continue;
                }

                if($content == "点歌"){
                    $word = "=========点歌=========".PHP_EOL;
                    $word .= "输入'点歌 水手',夏天就可以帮您点歌了".PHP_EOL;
                    $word .= "输入'歌词 水手',夏天还可以贴出来歌词哦".PHP_EOL;
                    $word .= "==========结束==========";
                    $this->sendTextMsg($word, $msg['FromUserName']);
                    continue;
                }
                if($content == "搜图"){
                    $word = "=========搜图=========".PHP_EOL;
                    $word .= "输入'搜图 斯嘉丽'".PHP_EOL;
                    $word .= "==========结束==========";
                    $this->sendTextMsg($word, $msg['FromUserName']);
                    continue;
                }
                if($content == "机器人"){
                    $word = "=======机器人======".PHP_EOL;
                    $word .= "发信息的时候 @夏天,夏天就可以和你聊天了".PHP_EOL;
                    $word .= "==========结束==========";
                    $this->sendTextMsg($word, $msg['FromUserName']);
                    continue;
                }

                if($content == "生活"){
                    $word = "==========生活===========".PHP_EOL;
                    $word .= "1.天气查询 ".PHP_EOL;
                    $word .= "发送 '北京天气'即可! ".PHP_EOL;
                    $word .= "2.查询快递 ".PHP_EOL;
                    $word .= "发送 '查询快递123456789' 即可! ".PHP_EOL;
                    $word .= "3.日期查询 ".PHP_EOL;
                    $word .= "发送 '今天农历多少' 即可! ".PHP_EOL;
                    $word .= "=======结束========";
                    $this->sendTextMsg($word, $msg['FromUserName']);
                    continue;
                }

                //=========================群===================================\\
                if (substr($msg['FromUserName'], 0, 2) == '@@') {
                    #在群里@我
                    if(strstr($content, "@夏天robot") !== false || strstr($content, "天气") !== false
                        || strstr($content, "查询快递") !== false || strstr($content, "农历") !== false ){
                        #图灵机器人
                        $this->sendTextMsg(CTools::robotTuling($content), $msg['FromUserName']);
                    }

                    $this->commonGames($content,$msg);

                    if($content ==  "群规"){
                            $this->sendTextMsg("本群禁止发表煽动性，政治性的言论...,", $msg['FromUserName']);
                    }
                    continue;
                }



                //==========================个人===========================\\
                if(strpos($msg['FromUserName'], '@@') === false){
                    #拉人进群功能
                    if($content == "拉我") {
                            foreach($this->wechat->group_users as $item){
                                if(in_array($item['NickName'],["夏天robot测试群","Vbot体验群"])){
                                    $chatRoomKehuId = $item['UserName'];
                                    break;
                                }
                            }
                            $this->sendInviteGroup($chatRoomKehuId,$msg['FromUserName']);
//                            if($res) $this->sendTextMsg("欢迎新人:".$res,$chatRoomKehuId);
                    }else{
                        if(!$this->commonGames($content,$msg))
                        $this->sendTextMsg(CTools::robotTuling($content), $msg['FromUserName']);
                    }

                }


            }
            #图片消息
            if ($msgType == 3) {

            }
            if($msgType == 37){
                //是否自动通过加好友验证
                $verifyMsg =  $msg['RecommendInfo']['Content'];
                #根据验证内容选择是否加入群聊中
                    $data = [
                        "Value" => $msg['RecommendInfo']['UserName'],
                        "VerifyUserTicket" => $msg['RecommendInfo']['Ticket']
                    ];
                echo "好友验证";
                    if($this->webwxverifyuser($data,3)){
                        $this->sendTextMsg("您好,我是机器人夏天，发送 '拉我' 进群,发送'功能'可以跟进一步了解夏天", $msg['RecommendInfo']['UserName']);
                    }

                }



            if($msgType == 51){
                #拉取所有群信息
                if(!empty($msg['StatusNotifyUserName'])){
                        $chatList = explode(',',$msg['StatusNotifyUserName']);
                        foreach($chatList as $username){
                            #群组
                            if (strpos($username, '@@') !== false){
                                $this->wechat->group_users_sync[$username] = $username;
                            }

                        }
                    #更新群信息
                    CTools::_echo("同步群信息");
                    $this->wechat->gethhMembers();


                }

            }
            #撤回消息
            if ($msgType == 10002) {
                if(isset($group_user_name)){
                    $user = $this->wechat->gethUserInfo(
                        [
                            'UserName' => $msg['FromUserName'],
                            'MemberUserName' => $group_user_name
                        ]
                    );
                }else{
                    $user = $this->wechat->gethUserInfo(['UserName' => $msg['FromUserName']]);
                }


                $msgId = $this->parseMsgId($content);
                $cache = \Yii::$app->cache;
                $content = $cache->get('WECHAT-MSG-'.$msgId);
                $this->sendTextMsg(sprintf('%s 刚撤回了消息: %s',$user['NickName'],$content), $msg['FromUserName']);
            }

            #系统消息
            if($msgType == 10000){
                if(strstr($content, "邀请") !== false){
                    preg_match('/(.*)邀请"(.*)"加入/', $content, $matches);

                    if(strstr($content, "邀请你加入了群聊") !== false){
                        $this->sendTextMsg("大家好,我是机器人夏天".PHP_EOL."小贴士:发送'功能'获取更多精彩", $msg['FromUserName']);
                    }

                    if(!empty($matches[2]))
                    $this->sendTextMsg("欢迎新人:".$matches[2].PHP_EOL."小贴士:发送'功能'获取更多精彩", $msg['FromUserName']);

                }
            }

        }
    }


    /**
     * 通用功能
     * @param $content
     * @param $msg
     */
    public function commonGames($content,$msg){
        $reply =false;
        $contentList =explode(" ",$content);
        if($contentList[0] == "点歌"){
            if(!empty($contentList[1])) {
                $this->sendMusicMsg($contentList[1], $msg['FromUserName']);
                $reply =true;
            }
        }
        if($contentList[0] == "歌词"){
            if(!empty($contentList[1])){
                $this->sendMusicMsg($contentList[1], $msg['FromUserName'],1);
                $reply =true;
            }

        }
        if($contentList[0] == "搜图" ){
            if(!empty($contentList[1])) {
                $this->sendImgMsg($contentList[1], $msg['FromUserName']);
                $reply =true;
            }
        }
        elseif($contentList[0] == "妹子"){
            $this->sendImgMsg($contentList[0], $msg['FromUserName'],1);
            $reply =true;
        }elseif($contentList[0] == "打赏夏天" || $contentList[0] == "打赏" ){
            $this->sendImgMsg($contentList[0], $msg['FromUserName'],2);
            $reply =true;
        }



        return $reply;
    }
    /**
     * 发送消息
     * @param $word
     * @param string $to
     * @return bool
     */
    public function sendTextMsg($word, $to = 'filehelper')
    {

        $word = CTools::emojiDecode($word);

        $url = sprintf($this->wechat->sessionKeys['base_url_prefix'] .
            '/webwxsendmsg?pass_ticket=%s', $this->wechat->sessionKeys['passTicket']);
        $clientMsgId = (time() * 1000) . substr(uniqid(), 0, 5);
        $params = [
            'BaseRequest' => $this->wechat->sessionKeys['baseRequest'],
            'Msg' => [
                "Type" => 1,
                "Content" => $word,
                "FromUserName" => $this->wechat->myself['UserName'],
                "ToUserName" => $to,
                "LocalID" => $clientMsgId,
                "ClientMsgId" => $clientMsgId
            ]
        ];
        $dic = CHttpWechat::curlPostJson($url, $this->wechat->webkit,$params);
        return $dic['BaseResponse']['Ret'] == 0;
    }


    /**
     *
     * 邀请参加群聊
     * @param $chatId
     * @param string $to
     * @return bool
     */
    public function sendInviteGroup($chatId,$to='filehelper'){
        $url = sprintf($this->wechat->sessionKeys['base_url_prefix'] .
            '/webwxupdatechatroom?fun=addmember');
        $params = [
            'BaseRequest' => $this->wechat->sessionKeys['baseRequest'],
            'ChatRoomName' => $chatId,
            'AddMemberList' => $to
        ];
        $dic = CHttpWechat::curlPostJson($url, $this->wechat->webkit,$params);
        return  $dic['BaseResponse']['Ret'] == 0 ? $dic['MemberList'][0]['NickName'] :false;
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
    }

    public function sendMusicMsg($word, $to = 'filehelper',$type=0){


        $url = 'http://music.163.com/api/search/get/web?csrf_token='.time().rand(1,100);
        $params =[
            'hlpretag' => "",
            'hlposttag' => "",
            's'=> $word,
            'type' => 1,
            'offset' =>0,
            'total' => true,
            'limit' => 1
        ];

        $json = CHttp::curlPost($url,$params);
        $data =json_decode($json,true);

        if($type ==0){
            if(!empty($data['result']['songs'])){
                $word .= "歌曲链接:\r\n";
                $word .= 'http://music.163.com/#/song/'.$data['result']['songs'][0]['id'];
            }else{
                $word .="查找结果:无";
            }
        }




        if($type ==1){
            if(!empty($data['result']['songs'])){
                $json  = file_get_contents("http://music.163.com/api/song/lyric?os=pc&id=".$data['result']['songs'][0]['id']."&lv=-1&kv=-1&tv=-1");
                $data = json_decode($json,true);
                if($data['code'] == 200 && !empty($data['lrc'])){
                    $word = $data['lrc']['lyric'];
                }else{
                    $word .="查找结果:无";
                }
            }else{
                $word .="查找结果:无";
            }
        }

        $url = sprintf($this->wechat->sessionKeys['base_url_prefix'] .
            '/webwxsendmsg?pass_ticket=%s', $this->wechat->sessionKeys['passTicket']);
        $clientMsgId = (time() * 1000) . substr(uniqid(), 0, 5);
        $params = [
            'BaseRequest' => $this->wechat->sessionKeys['baseRequest'],
            'Msg' => [
                "Type" => 1,
                "Content" => $word,
                "FromUserName" => $this->wechat->myself['UserName'],
                "ToUserName" => $to,
                "LocalID" => $clientMsgId,
                "ClientMsgId" => $clientMsgId
            ]
        ];
        $dic = CHttpWechat::curlPostJson($url, $this->wechat->webkit,$params);
        return $dic['BaseResponse']['Ret'] == 0;


    }

    public function sendImgMsg($word, $to = 'filehelper',$type =0){

        if($type == 0)  $img = CTools::getSearchImgFile($word);
        if($type == 1)  $img = CTools::getSearchImgMn($word);
        if($type == 2)  $img = CTools::getSearchImgDs($word);
        if($img){
            $res = $this->uploadFile($img,$to);
            $url = $this->wechat->sessionKeys['base_url_prefix'] .'/webwxsendmsgimg?fun=async&f=json&lang=zh_CN';
            $clientMsgId = (time() * 1000) . substr(uniqid(), 0, 5);
            $params = [
                'BaseRequest' => $this->wechat->sessionKeys['baseRequest'],
                'Msg' => [
                    "Type" => 3,
                    "MediaId" => $res['MediaId'],
                    "FromUserName" => $this->wechat->myself['UserName'],
                    "ToUserName" => $to,
                    "LocalID" => $clientMsgId,
                    "ClientMsgId" => $clientMsgId
                ]
            ];
            $dic = CHttpWechat::curlPostJson($url, $this->wechat->webkit,$params);
            return $dic['BaseResponse']['Ret'] == 0;
        }else{
            $this->sendTextMsg('没有找到图片，有可能是网络问题，建议重试一次',$to);
        }

    }


    /**
     * 上传附件
     * @param $file
     * @param $username
     * @return bool
     */
    public  function uploadFile($file_name,$username)
    {
        $urlList= parse_url($this->wechat->sessionKeys['base_url_prefix']);
        $url = "https://file.".$urlList['host'].$urlList['path'].'/webwxuploadmedia?f=json';

        #获取cookie ticket
        $webwx_data_ticket ="";
        $fp = fopen(\Yii::$app->basePath . "/runtime/wechat/cookie/cookie.".$this->wechat->session, 'r');
        while ($line = fgets($fp)) {
            # code...
            if (strpos($line, 'webwx_data_ticket') !== false) {
                $arr = explode("\t", trim($line));
                $webwx_data_ticket = $arr[6];
                break;
            }
        }
        fclose($fp);
        if (empty($webwx_data_ticket)) CTools::_echo("webwx_data_ticket failed");
        $image_name = $file_name;
        $file_size = filesize($file_name);

        $info = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($info, $image_name);
        finfo_close($info);

        $uploadmediarequest = CTools::json_encode([
            "BaseRequest" => $this->wechat->sessionKeys['baseRequest'],
            "ClientMediaId" => (time() * 1000).mt_rand(10000,99999),
            "TotalLen" => $file_size,
            "StartPos" => 0,
            "DataLen" => $file_size,
            "MediaType" => 4,
            "UploadType" => 2,
            "FromUserName" => $this->wechat->myself["UserName"],
            "ToUserName" => $username,
            "FileMd5" => md5_file($image_name)
        ]);

        $multipart_encoder = [
            'id' => 'WU_FILE_0',
            'name' => basename($file_name),
            'type' => $mime_type,
            'lastModifiedDate' => gmdate('D M d Y H:i:s TO', filemtime($file_name)).' (CST)',
            'size' => $file_size,
            'mediatype' => 'pic',
            'uploadmediarequest' => $uploadmediarequest,
            'webwx_data_ticket' => $webwx_data_ticket,
            'pass_ticket' => $this->wechat->sessionKeys['passTicket'],
            'filename'  =>new \CURLFile(realpath($file_name),$mime_type,basename($file_name)),
        ];
        $response_json = CHttpWechat::curlPostFile($url, $this->wechat->webkit,$multipart_encoder,$image_name);

        return $response_json['BaseResponse']['Ret'] == 0 ?   $response_json : false;

    }
    /**
     * 验证通过好友申请
     */
    public function webwxverifyuser($user){
        $url = sprintf($this->wechat->sessionKeys['base_url_prefix'].'/webwxverifyuser?lang=zh_CN&r=%s&pass_ticket=%s' ,time()*1000, $this->wechat->sessionKeys['passTicket']);

        $params = [
            "BaseRequest"=> $this->wechat->sessionKeys['baseRequest'],
            "Opcode"=>3,
            "VerifyUserListSize"=>1,
            "VerifyUserList"=>[$user],
            "VerifyContent"=>"",
            "SceneListCount"=>1,
            "SceneList"=>[33],
            "skey"=>$this->wechat->sessionKeys['Skey']
        ];
        $dic = CHttpWechat::curlPostJson($url, $this->wechat->webkit,$params);
        return $dic['BaseResponse']['Ret'] == 0;
    }

    #撤回信息
    public static function cacheMsg($id,$content){
        // 加载缓存组件
        $cache = \Yii::$app->cache;
        // 添加一个缓存
        $cache->set('WECHAT-MSG-'.$id,$content,60*2);

    }

    /**
     * 解析message获取msgId.
     *
     * @param $xml
     *
     * @return string msgId
     */
    private function parseMsgId($xml)
    {

        preg_match('/<msgid>(\d+)<\/msgid>/', $xml, $matches);
        return $matches[1];
    }


    /**
     * 把请求数组转为multipart模式.
     *
     * @param $data
     *
     * @return array
     */
    private static function _dataToMultipart($data,$file)
    {
        $result = [];

        foreach ($data as $key => $item) {
            $field = [
                'name'     => $key,
                'contents' => $item,
            ];
            if ($key === 'filename') {
                $field['filename'] = basename($file);
            }
            $result[] = $field;
        }

        return $result;
    }
}

